package com.jcw.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcw.common.R;
import com.jcw.domain.AddressBook;
import com.jcw.service.AddressBookService;
import com.jcw.mapper.AddressBookMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;

/**
 * @author JCW
 * @description 针对表【address_book(地址管理)】的数据库操作Service实现
 * @createDate 2023-03-30 11:19:30
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook>
        implements AddressBookService {

    @Resource
    private HttpSession session;

    @Override
    public R<String> editDefault(AddressBook addressBook) {
        Long userId = (Long) session.getAttribute("user");
        Long addressBookId = addressBook.getId();
        update().eq("user_id", userId).set("is_default", 0).update();
        update().eq("id", addressBookId).set("is_default", 1).update();
        return R.success("设置默认地址成功");
    }

    @Override
    public R<String> add(AddressBook addressBook) {
        addressBook.setUserId((Long) session.getAttribute("user"));
        save(addressBook);
        return R.success("添加成功");
    }

    @Override
    public R<AddressBook> echoAddr(Long id) {
        AddressBook addressBook = query().eq("id", id).one();
        return R.success(addressBook);
    }

    @Override
    public R<String> editAddr(AddressBook addressBook) {
        updateById(addressBook);
        return R.success("更新成功");
    }

    @Override
    public R<String> delete(String ids) {
        boolean removed = update().eq("is_default", 0).eq("id", ids).remove();
        if (removed) {
            return R.success("删除成功");
        }
        return R.error("删除失败，可能是默认地址");
    }

    @Override
    public R<AddressBook> defaultAddr() {
        Long userID = (Long) session.getAttribute("user");
        AddressBook addressBook = query().eq("user_id", userID).eq("is_default", 1).one();
        return R.success(addressBook);
    }
}




